import { expect } from "chai";
import * as fs from "fs";
import { IKey, KeyBox} from "../src/KeyBox";

describe( "测试KeyBox", () => {
    let keybox: KeyBox;

    it( "create", () => {
        KeyBox.deleteFolderRecursive( "testdata");
        expect( KeyBox.load( "testdata")).to.equal( null);

        keybox = KeyBox.create( "passwd12345", "testdata");
        const mainKeyPath = "testdata/mainKeys";
        let exist = fs.existsSync( mainKeyPath);
        expect( exist).to.equal(true);
        exist = fs.existsSync( mainKeyPath + "/key.public");
        expect( exist).to.equal(true);
        exist = fs.existsSync( mainKeyPath + "/key.private");
        expect( exist).to.equal(true);

        expect( keybox.decrypt( keybox.encrypt( "what's up man"))).to.equal( "what's up man");
    });
    it( "load", () => {
        const kb = KeyBox.load( "testdata");
        expect( kb.publicKey).to.equal( keybox.publicKey);
        expect( kb.checkPassword( "wrongpassword")).to.equal(false);
        expect( kb.checkPassword( "passwd12345")).to.equal(true);
        expect( kb.privateKey).to.equal( keybox.privateKey);

        expect( kb.decrypt( keybox.encrypt( "what's up man"))).to.equal( "what's up man");
    });
    it( "changeMainPassword", () => {
        keybox.changeMainPassword( "newpassword");
        const kb = KeyBox.load( "testdata");

        expect( kb.publicKey).to.equal( keybox.publicKey);
        expect( kb.checkPassword( "passwd12345")).to.equal(false);
        expect( kb.checkPassword( "newpassword")).to.equal(true);
        expect( kb.privateKey).to.equal( keybox.privateKey);

        expect( kb.decrypt( keybox.encrypt( "what's up man"))).to.equal( "what's up man");
    });
    it( "createAndLoadKeys", () => {
        const d = new Date();
        const k1: IKey = {
            desc: "desc", keyid: "xxx1",
            lastUpdated: new Date().toLocaleDateString(), password: "passwd1234",
            url: "http://www.www.com", user: "abc",
        };
        keybox.saveKey( k1, true, false);
        const keys = keybox.loadKeys();
        expect( keys.length).to.equal( 1);
        const k2 = keys[0];
        expect( JSON.stringify(k1)).to.equal( JSON.stringify(k2));
    });
});
